package com.giveme5.common.api.interceptor;

import javax.servlet.http.HttpServletResponse;

import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;

import com.giveme5.common.api.entity.SimpleAdaptorError;
import com.giveme5.common.api.entity.SimpleValidationError;
import com.giveme5.common.api.exception.AdaptorErrorException;
import com.giveme5.common.api.exception.ApiAdaptorErrorContext;
import com.giveme5.common.api.exception.ValidationErrorException;
import com.giveme5.common.entity.SimpleResult;
import com.giveme5.common.entity.SimpleResultMessage.CommonResultCode;
import com.giveme5.common.exception.SimpleException;
import com.giveme5.util.validation.Errors;

@IocBean(name = "apiErrorInterceptor")
public class ApiErrorInterceptor implements MethodInterceptor {

	@Override
	public void filter(InterceptorChain chain) throws Throwable {
		try {
			Object[] args = chain.getArgs();
			for (int i = 0; i < args.length; i++) {
				Object object = args[i];
				if (object instanceof Errors && ((Errors) object).hasError()) {
					// 发生校验错误,直接返回.
					SimpleValidationError sve = new SimpleValidationError();
					sve.setErrors(((Errors) object).getErrorsList());
					throw new ValidationErrorException(sve);
				}
				if (object instanceof ApiAdaptorErrorContext) {
					// 发生数据类型错误
					SimpleAdaptorError sae = new SimpleAdaptorError();
					sae.setErrors(((ApiAdaptorErrorContext) object).getErrorMsgs());
					throw new AdaptorErrorException(sae);
				}
			}
			chain.doChain();
		} catch (Throwable t) {
			HttpServletResponse resp = Mvcs.getResp();
			resp.setHeader("Access-Control-Allow-Origin", "*");
			resp.setHeader("Cache-Control", "no-cache");
			if (t instanceof SimpleException) {
				// 逻辑异常
				resp.setStatus(500);
				Mvcs.write(resp, ((SimpleException) t).getResult(), null);
			} else {
				// 未处理异常
				t.printStackTrace();
				resp.setStatus(500);
				SimpleResult result = new SimpleResult(CommonResultCode.COMMON_ERROR);
				Mvcs.write(resp, result, null);
			}
		}

	}
}
